<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>推广链接管理</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/layui.css')}}" media="all">
  <link rel="stylesheet" href="{{asset('/layuiadmin/style/admin.css')}}" media="all">
  <style>
    .edit{background-color: #ed9c3a;}
    .shenhe{background-color: #429488;}    
    .see{background-color: #7cb717;} 
    .cur{color:#009688;}
    .del {background-color: #e85052;}
    .userbox,.storebox{height:190px;margin-right:0; overflow-y: auto; z-index: 999; position: absolute; left: 0px; top: 63px; width:298px; background-color:#ffffff; border: 1px solid #ddd;}
    .userbox .list,.storebox .list{height:38px;line-height: 38px;cursor:pointer; padding-left:10px;}
    .userbox .list:hover,.storebox .list:hover{background-color:#eeeeee;}
  </style>
</head>
<body>

  <div class="layui-fluid">
    <div class="layui-row layui-col-space15">
      <div class="layui-col-md12">
        <div class="layui-fluid">
          <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
              <div class="layui-card"> 
                <div class="layui-card-header">推广链接管理</div>
                <div class="layui-card-body">
                  <div class="layui-btn-container" style="font-size:14px;display: inline-flex;">
                    <a class="layui-btn layui-btn-primary" lay-href="{{url('/user/addad')}}" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block;width: 122px;">添加推广链接</a>
                    <a class="layui-btn layui-btn-primary" id="batchDel" style="background-color:#3475c3;border-radius: 5px;border:none;color:#fff;display: block;width: 122px;">批量删除</a>
                  </div>
                  
                  <div class="layui-form" lay-filter="component-form-group" style="display: inline-block;">
                      <div class="layui-form-item" style="display: inline-block;">       
                          <div class="layui-inline">                   
                              <div class="layui-input-inline" style="width:350px">
                                  <label class="layui-form-label">门店名称:</label>
                                  <div class="layui-input-block">
                                  <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入门店名称" class="layui-input inputstore">
                                  <div class="storebox" style='display: none'></div>
                              </div>
                              </div>
                          </div>
                      </div>
                      <div class="layui-form-item" style="display: inline-block;">       
                          <div class="layui-inline">                   
                              <div class="layui-input-inline" style="width:350px">
                                  <label class="layui-form-label">推广链接:</label>
                                  <div class="layui-input-block">
                                  <input type="text" style="border-radius:5px" name="adurl" autocomplete="off" placeholder="请输入推广链接" class="layui-input adUrlInput">
                              </div>
                              </div>
                          </div>
                      </div>
                      <div class="layui-inline" style="display: inline-block;">
                          <button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="LAY-app-contlist-search" style="border-radius:5px;margin-top:-5px;margin-bottom: 0;height:36px;line-height: 36px;">
                              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                          </button>
                      </div>
                  </div>
                  <table class="layui-hide" id="test-table-page" lay-filter="test-table-page"></table>
                  <!--<script type="text/html" id="time">-->
                  <!--  @{{ d.s_time }}--@{{ d.e_time }}-->
                  <!--</script>-->
                  <script type="text/html" id="table-content-list">
                    <a class="layui-btn layui-btn-normal layui-btn-xs del" lay-event="del">删除</a>
                  </script>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <input type="hidden" class="user_id">
  <input type="hidden" class="status">
  <input type="hidden" class="store_id">
<!-- 操作按钮 -->
<!-- 
                    
<a class="layui-btn layui-btn-normal layui-btn-xs see" lay-event="detail">查看</a> -->
  <script src="{{asset('/layuiadmin/layui/layui.js')}}"></script> 
    <script>
    var token = localStorage.getItem("Usertoken");
    layui.config({
      base: '../../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index','form', 'table','laydate'], function(){
        var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,form = layui.form
            ,laydate = layui.laydate;

        // 未登录,跳转登录页面
        $(document).ready(function(){        
            if(token==null){
                window.location.href="{{url('/user/login')}}"; 
            }
        });

        // 选中的id和值数组
        var selectedIds = [];
        var selectedValues = [];
        table.render({
            elem: '#test-table-page'
            ,url: "{{url('/api/ad/ad_lists')}}"
            ,method: 'post'
            ,where:{
              token:token
            }
            ,request:{
              pageName: 'p', 
              limitName: 'l'
            }
            ,page: true
            ,cellMinWidth: 150
            ,cols: [[
                {type: 'checkbox'}
                ,{field:'id', title: 'ID',width:100}
                ,{field:'ad_url', title: '推广链接'}
                ,{field:'store_key_ids', title: '门店ID',width:220}
                 ,{field:'store_name', title: '门店名称',width:260}
                ,{width:200,align:'center', fixed: 'right', toolbar: '#table-content-list',title: '操作'}
            ]]
            ,response: {
                statusName: 'status' //数据状态的字段名称，默认：code
                ,statusCode: 1 //成功的状态码，默认：0
                ,msgName: 'message' //状态信息的字段名称，默认：msg
                ,countName: 't' //数据总数的字段名称，默认：count
                ,dataName: 'data' //数据列表的字段名称，默认：data
              } 
            ,done: function(res, curr, count){
//              console.log(res);
              $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
              // 手动触发复选框选中
              table_data = res.data;//初始化数据;此处接收的是当前页的这10条数据
              if (selectedIds.length > 0) {
                  for (var i = 0; i < selectedIds.length; i++) {
                      for (var j = 0; j < table_data.length; j++) {
                          if (selectedIds[i] == table_data[j].id) {//匹配上就设为选中
                              //回显checkbox
                              $('.layui-table tr[data-index=' + j + '] input[type="checkbox"]').attr("checked", "checked");
                              form.render('checkbox');
                          }
                      }
                  }
              }
            }
        });

        table.on('tool(test-table-page)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
          var e = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          var tr = obj.tr; //获得当前行 tr 的DOM对象
//          console.log(e);
          // localStorage.setItem('s_store_id', e.store_id);

          if(layEvent === 'del'){
            layer.confirm('确认删除此消息?',{icon: 2}, function(index){
              $.post("{{url('/api/ad/ad_del')}}",
              {
                 token:token
                  ,id:e.id
              },function(res){
//                  console.log(res);
                  if(res.status==1){
                    obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                    layer.close(index);
                    layer.msg(res.message, {
                      offset: '50px'
                      ,icon: 1
                      ,time: 2000
                    });
                  }else{
                    layer.msg(res.message, {
                        offset: '50px'
                        ,icon: 2
                        ,time: 3000
                    });
                  }
              },"json");
              
            });
          }else if(layEvent === 'see'){
            layer.open({
              type: 2,
              title: '详细',
              shade: false,
              maxmin: true,
              area: ['90%', '80%'],
              content: "{{url('/user/adsee?')}}"+e.id
            });
          }else if(layEvent === 'edit'){
            localStorage.setItem('ad_p_id', e.ad_p_id);
            localStorage.setItem('user_ids', e.user_ids);
            localStorage.setItem('store_key_ids', e.store_key_ids);
            
            $('.edit').attr('lay-href',"{{url('/user/editad?')}}"+e.id);
          }

        });

        // 选择学校
        form.on('select(schooltype)', function(data){
          var type = data.value;
          
          //执行重载
          table.reload('test-table-page', {
            where: { 
              type: type
            }
            ,page: {
              curr: 1 //重新从第 1 页开始
            }
          });
        });

        //监听搜索
        form.on('submit(LAY-app-contlist-search)', function(data){
          var value = $('.store_id').val()
          let ad_url = data.field.adurl
          //执行重载
          table.reload('test-table-page', {
            where: {
              store_id: value,
              ad_url:ad_url
            }
            ,page: {
              curr: 1 //重新从第 1 页开始
            }
          });
        });
        
        $(".inputstore").bind("input propertychange",function(event){
            var store_name = $(this).val();
            if (store_name.length == 0) {
                $('.storebox').html('');
                $('.storebox').hide();
                $('.store_id').val('')
            } else {
                $.post("{{url('/api/user/store_lists')}}",
                {
                    token:token
                    ,store_name:$(this).val()
                    ,l:100
                },function(res){
                    var html="";
                    if(res.t==0){
                        $('.storebox').html('');
                    }else{
                        for(var i=0;i<res.data.length;i++){
                            html+='<div class="list" data='+res.data[i].store_id+'>'+res.data[i].store_name+'</div>'
                        }
                        $(".storebox").show();
                        $('.storebox').html('');
                        $('.storebox').append(html);
                    }
                },"json");
            }
        });

        $(".storebox").on("click",".list",function(){
            $('.inputstore').val($(this).html());
            $('.store_id').val($(this).attr('data'));
            $('.storebox').hide();
        });

      table.on('checkbox(test-table-page)', function(obj) {
        var row = obj.data;
        if (obj.checked) {
          if (obj.type == 'one') {//勾选单条
            if (!selectedIds.includes(row.id)) {
                selectedIds.push(row.id);
                selectedValues.push(row);
            }
          }
          if (obj.type == 'all') {//勾选全部
              for (var i = 0; i < table_data.length; i++) {
                if (!selectedIds.includes(table_data[i].id)) {
                    selectedIds.push(table_data[i].id);
                    selectedValues.push(table_data[i]);
                }
              }
          }
        } else {
          if (obj.type == 'one') {
            // 从数组中移除
            var index = selectedIds.indexOf(row.id);
            if (index !== -1) {
                selectedIds.splice(index, 1);
                selectedValues.splice(index,1);
            }
          }else{
            for (var i = 0; i < selectedIds.length; i++) {
              for (var j = 0; j < table_data.length; j++) {
                  if (selectedIds[i] == table_data[j].id) {
                    selectedIds = selectedIds.filter(function (item) {
                      return item != selectedIds[i];
                    });
                  }
              }
            }
            for (var i = 0; i < selectedValues.length; i++) {
              for (var j = 0; j < table_data.length; j++) {
                  if (selectedValues[i].id == table_data[j].id) {
                    selectedValues = selectedValues.filter(function (item) {
                      return item.id != selectedValues[i].id;
                    });
                  }
              }
            }
          }
            
        }
        console.log('当前选中ID：', selectedIds);
        console.log('当前选中value：', selectedValues);
      });

      // 批量删除
      $('#batchDel').click(function(){
        if(selectedIds.length == 0){
          layer.msg('请先选择需要删除的数据！')
          return
        }
        if(selectedIds.length>100){
          layer.msg('一次最多选择100条数据！')
          return
        }
        layer.confirm('确认删除此消息?',{icon: 2}, function(index){
          var pageLoading = layer.msg('数据处理中..', {
            icon: 16
            ,shade: 0.3
            ,time: false
          });
          selectedIds.forEach((ele,index) => {
            let params = {
                token:token,
                id:ele
              }
              $.post("{{url('/api/ad/ad_del')}}",
                  params,function(res){
                      if(res.status==1){
                        if(index === selectedIds.length - 1){
                          layer.msg(res.message, {
                              offset: '50px'
                              ,icon: 1
                              ,time: 2000
                          });
                        }
                      }else{
                          layer.msg(res.message, {
                              offset: '50px'
                              ,icon: 2
                              ,time: 2000
                          });
                      }
                  },"json");
                if(index === selectedIds.length - 1){ //最后一个
                    setTimeout(() => {
                        selectedIds = [];
                        selectedValues = [];
                        storeSelData = [];
                        //执行重载
                        layer.closeAll();
                        table.reload('test-table-page', {
                            where: {
                            },
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                        
                    }, 2000);
                }
          });
        })
      })

    });

  </script>

</body>
</html>
